package com.school.controller;

import java.io.File;
import java.net.Inet4Address;
import java.net.InetAddress;
import java.net.NetworkInterface;
import java.net.UnknownHostException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.Enumeration;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Timer;
import java.util.TimerTask;
import java.util.UUID;

import javax.servlet.http.HttpServletResponse;

import org.apache.commons.io.FilenameUtils;
import org.apache.http.HttpResponse;
import org.apache.http.util.EntityUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MultipartFile;

import com.school.entity.HljtDevice;
import com.school.entity.HljtDuty;
import com.school.entity.HljtSchool;
import com.school.entity.HljtSchoolimage;
import com.school.entity.HljtSchoolnotify;
import com.school.entity.android.Head;
import com.school.entity.web.BasicsInfo;
import com.school.entity.web.Duty;
import com.school.service.HljtOtherInterfacesService;
import com.school.service.impl.HljtDutySerivceImpl;
import com.school.service.impl.HljtEducationSerivceImpl;
import com.school.service.impl.HljtSchoolNotifyServiceImpl;
import com.school.service.impl.HljtSchoolServiceImpl;
import com.school.util.HttpUtils;
import com.school.util.JsonInterface;
import com.school.util.Message;
import com.school.util.RepUtil;
import com.school.util.WhetherNotToUpdate;

import net.sf.json.JSONObject;

@Controller
public class HljtSchoolController {

	@Autowired
	private HljtSchoolServiceImpl schoolServiceImpl;
	@Autowired
	private HljtDutySerivceImpl hljtDutySerivceImpl;
	@Autowired
	private HljtSchoolNotifyServiceImpl hljtSchoolNotifyServiceImpl;
	@Autowired
	private HljtSchoolServiceImpl hljtSchoolServiceImpl;
	@Autowired
	private HljtEducationSerivceImpl hljtEducationSerivceImpl;
	@Autowired
	HljtOtherInterfacesService hljtOtherInterfacesService;
	
	/**
	 * 安卓端头部接口
	 * @return
	 * @throws Exception 
	 */
	@RequestMapping("/head")
	@ResponseBody
	public JsonInterface selectSchool() throws Exception {
		HljtSchool hljtSchool =hljtSchoolServiceImpl.findSchool();
		JsonInterface jsonInterface=new JsonInterface();
		String newIp= WhetherNotToUpdate.getIp();
		if(null!=hljtSchool) {
			String cityWeather =hljtSchool.getCityweather();
			
			String wendu=null;
			String tianqi=null;
			String city=null;
			if(null!=cityWeather&&cityWeather.length()>0) {
				city=hljtSchool.getCityweather();
				JSONObject json_test = JSONObject.fromObject(city);  
				JSONObject jsons =json_test.getJSONObject("data").getJSONArray("forecast").getJSONObject(0);
				String time=jsons.getString("predictDate");
				SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd");
				Date date = new Date();
				if(format.format(date).equals(time)) {
					System.out.println("有正确数据");
					city=hljtSchool.getCityweather();
					JSONObject json_testa = JSONObject.fromObject(city);  
					JSONObject jsonsa =json_testa.getJSONObject("data").getJSONArray("forecast").getJSONObject(0);
					wendu=jsonsa.getString("tempDay")+"℃ ～ "+jsonsa.getString("tempNight")+"℃";
					tianqi =jsonsa.getString("conditionDay");
				}else {
					System.out.println("有错误数据修改");
					city=this.getCitys(hljtSchool.getCityid()+"");
					BasicsInfo basicsInfo=new BasicsInfo();
					basicsInfo.setCityweather(city);
					schoolServiceImpl.setSchool(basicsInfo);
					JSONObject json_testa = JSONObject.fromObject(city);  
					JSONObject jsonsa =json_testa.getJSONObject("data").getJSONArray("forecast").getJSONObject(0);
					wendu=jsonsa.getString("tempDay")+"℃ ～ "+jsonsa.getString("tempNight")+"℃";
					tianqi =jsonsa.getString("conditionDay");
				}
			}else {
				
				System.out.println("没有数据添加");
				city=this.getCitys(hljtSchool.getCityid()+"");
				BasicsInfo basicsInfo=new BasicsInfo();
				basicsInfo.setCityweather(city);
				schoolServiceImpl.setSchool(basicsInfo);
				JSONObject json_test = JSONObject.fromObject(city);  
				JSONObject jsons =json_test.getJSONObject("data").getJSONArray("forecast").getJSONObject(0);
				wendu=jsons.getString("tempDay")+"℃ ～ "+jsons.getString("tempNight")+"℃";
				tianqi =jsons.getString("conditionDay");
			}
			
			
			
			Head Head=new Head();
			HljtSchool list=schoolServiceImpl.findSchool();
			if(list !=null) {
	 
				Head.setNewTime(new Date().getTime()+"");
				Head.setSchoolName(list.getSchoolname());
				Head.setSchoolLogo(newIp+list.getLogo());

				Head.setCityweather(tianqi);
				Head.setTemperature(wendu);
				JSONObject json = JSONObject.fromObject(Head);
				jsonInterface.setData(json.toString());
				jsonInterface.setErrCode(0);
				jsonInterface.setErrMsg("请求成功");
			}else {
				JSONObject json = JSONObject.fromObject(null);
				jsonInterface.setData(json.toString());
				jsonInterface.setErrCode(1);
				jsonInterface.setErrMsg("无数据，请添加数据！");
			}
		}else {
			Head Head=new Head();
			System.out.println(new Date().getTime()+"");
			Head.setNewTime(new Date().getTime()+"");
			JSONObject json = JSONObject.fromObject(Head);
			jsonInterface.setData(json.toString());
			jsonInterface.setErrCode(0);
			jsonInterface.setErrMsg("请求成功");
		}
	return jsonInterface;
}
//====================================================================web================================================================================
	/**
	 * 查找德育模块
	 * @param rep
	 * @return
	 * @throws Exception
	 */
	@RequestMapping("/selecteducation")
	@ResponseBody
	public Message selectEducation(HttpServletResponse rep) throws Exception{
		RepUtil.repPake(rep);
		Message Message=new Message();
		Map<String, Object> data =new HashMap<>();
		String newIp= WhetherNotToUpdate.getIp();
		List<HljtDuty> DutyList=hljtDutySerivceImpl.findAll();
		List<Duty> dutys=new ArrayList<>();
		if(null!=DutyList&&DutyList.size()>0) {
			for(int i=0;i<DutyList.size();i++) {
				Duty duty=new Duty();
				
				duty.setId(DutyList.get(i).getId());
				duty.setDutyname(DutyList.get(i).getDutyname());
				duty.setDutyimage(newIp+DutyList.get(i).getDutyimage());
				duty.setProportion(DutyList.get(i).getProportion());
				dutys.add(duty);
			}
			data.put("data", dutys);
			data.put("success", true);
		}else {
			data.put("data", dutys);
			data.put("success", true);
		}
		
		Message.setData(data);
		return Message;
	}
	
	/**
	 * 修改德育模式
	 * @param id
	 * @param dutyname
	 * @param proportion
	 * @param imgFile
	 * @param rep
	 * @return
	 * @throws Exception
	 */
	@RequestMapping("/updateeducation")
	@ResponseBody
	public Message updateEducation(Integer id,String dutyname,Integer proportion,MultipartFile imgFile,HttpServletResponse rep) throws Exception{
		RepUtil.repPake(rep);
		Message Message=new Message();
		Map<String, Object> data =new HashMap<>();
		String newIp= WhetherNotToUpdate.getIp();
		if(null !=id&&null!=dutyname && null !=proportion) {
				if(imgFile.getSize()>0) {
					//生成新的图片名字
					String name = UUID.randomUUID().toString().replaceAll("-", "");
					//图片后缀名
					String ext = FilenameUtils.getExtension(imgFile.getOriginalFilename());
					Date date=new Date();
					//保存路径D:\java\apache-tomcat-8.0.48\webapps\image\class
					imgFile.transferTo(new File(WhetherNotToUpdate.getSaveDisk() + name + "." + ext));
					String image=name+"."+ext;
					HljtDuty hljtDuty=new HljtDuty();
					
					hljtDuty.setId(id);
					hljtDuty.setDutyname(dutyname);
					hljtDuty.setDutyimage(WhetherNotToUpdate.getReadDisk()+image);
					hljtDuty.setProportion(proportion);
					hljtDutySerivceImpl.updateDuty(hljtDuty);
					data.put("success", true);
				}else {
					HljtDuty  HljtDuty=hljtDutySerivceImpl.selectDuty(id);
					String image=HljtDuty.getDutyimage();
					HljtDuty hljtDuty=new HljtDuty();
					hljtDuty.setId(id);
					hljtDuty.setDutyname(dutyname);
					hljtDuty.setDutyimage(image);
					hljtDuty.setProportion(proportion);
					hljtDutySerivceImpl.updateDuty(hljtDuty);
					data.put("success", true);
				}
		}else {
			data.put("success", false);
		}
		Message.setData(data);
		return Message;
		
	}
	
	/**
	 * 添加德育模块
	 * @param dutyname
	 * @param proportion
	 * @param imgFile
	 * @param rep
	 * @return
	 * @throws Exception
	 */
	@RequestMapping("/addeducation")
	@ResponseBody
	public Message addEducation(String dutyname,Integer proportion,MultipartFile imgFile,HttpServletResponse rep) throws Exception{
		RepUtil.repPake(rep);
		Message Message=new Message();
		Map<String, Object> data =new HashMap<>();
		if(null !=dutyname && null !=proportion &&imgFile.getSize()>0) {
				HljtDuty hljtDuty=new HljtDuty();
				//生成新的图片名字
				String name = UUID.randomUUID().toString().replaceAll("-", "");
				//图片后缀名
				String ext = FilenameUtils.getExtension(imgFile.getOriginalFilename());
				//保存路径D:\java\apache-tomcat-8.0.48\webapps\image\class
				imgFile.transferTo(new File(WhetherNotToUpdate.getSaveDisk() + name + "." + ext));
				String image=name+"."+ext;
				hljtDuty.setDutyname(dutyname);
				hljtDuty.setDutyimage(WhetherNotToUpdate.getReadDisk()+image);
				hljtDuty.setProportion(proportion);
				
				hljtDutySerivceImpl.addDuty(hljtDuty);
				
			data.put("success", true);
		}else {
			data.put("success", false);
		}
		Message.setData(data);
		return Message;
	}
	
	/**
	 * 德育模块删除
	 * @param id
	 * @param rep
	 * @return
	 */
	@RequestMapping("/deleteEducation")
	@ResponseBody
	public Message deleteEducation(Integer id,HttpServletResponse rep){
		RepUtil.repPake(rep);
		Message Message=new Message();
		Map<String, Object> data =new HashMap<>();
		if(null !=id) {
			hljtDutySerivceImpl.deleteDuty(id);
			hljtEducationSerivceImpl.deleteEducationall(id);
			data.put("success", true);
		}else {
			data.put("success", false);
		}
		Message.setData(data);
		return Message;
	}
	/**
	 * 查找学校通知
	 * @param title
	 * @param type
	 * @param pageSize
	 * @param pageIndex
	 * @param rep
	 * @return
	 */
	@RequestMapping("/selectschoolnotice")
	@ResponseBody
	public Message selectSchoolnotice(String title,String type,Integer pageSize,Integer  pageIndex,HttpServletResponse rep){
		RepUtil.repPake(rep);
		Message Message=new Message();
		Map<String, Object> data =new HashMap<>();
		if(null != type) {
			if(null != title) {
				pageIndex=(pageIndex-1)*pageSize;
				List<HljtSchoolnotify>  Schoolnotifyall=hljtSchoolNotifyServiceImpl.findSchoolnotifypage(title, pageSize, pageIndex, type);
				List<HljtSchoolnotify>  Schoolnotify=hljtSchoolNotifyServiceImpl.findSchoolnotifypage(title, null, null, type);
				
				data.put("data", Schoolnotifyall);
				data.put("Totle", Schoolnotify.size());
				data.put("success", true);
			}else {
				title=null;
				pageIndex=(pageIndex-1)*pageSize;
				List<HljtSchoolnotify>  Schoolnotifyall=hljtSchoolNotifyServiceImpl.findSchoolnotifypage(title, pageSize, pageIndex, type);
				List<HljtSchoolnotify>  Schoolnotify=hljtSchoolNotifyServiceImpl.findSchoolnotifypage(title, null, null, type);
				
				data.put("data", Schoolnotifyall);
				data.put("Totle", Schoolnotify.size());
				data.put("success", true);
			}
		}else {
			data.put("success", false);
		}
		Message.setData(data);
		return Message;
	}
	
	/**
	 * 修改一条数据
	 * @param id
	 * @param title
	 * @param content
	 * @param type
	 * @param voice
	 * @param fullscreen
	 * @param rep
	 * @return
	 */
	@RequestMapping("/updateschoolnotice")
	@ResponseBody
	public Message updateSchoolnotice(Integer id,String title,String content,String type,Integer voice,Integer fullscreen ,HttpServletResponse rep){
		RepUtil.repPake(rep);
		Message Message=new Message();
		Map<String, Object> data =new HashMap<>();
		
		if(null !=id&&null!=title&&null!=content&&null!=type&&null!=voice&&null!=fullscreen) {
			HljtSchoolnotify hljtschoolnotify=new HljtSchoolnotify();
			hljtschoolnotify.setId(id);
			hljtschoolnotify.setTitle(title);
			hljtschoolnotify.setContent(content);
			hljtschoolnotify.setVoice(voice);
			hljtschoolnotify.setFullscreen(fullscreen);
			Date createtime=new Date();
			hljtschoolnotify.setCreatetime(createtime);
			
			hljtSchoolNotifyServiceImpl.updateSchoolnotify(hljtschoolnotify);
			HljtDevice hljtDevice = new HljtDevice();
			hljtDevice.setPattern(2);
			hljtOtherInterfacesService.updateDeviceAllModify(hljtDevice);
			data.put("success", true);
		}else {
			data.put("success", false);
		}
		Message.setData(data);
		return Message;
	}
	/**
	 * 添加条通知
	 * @param title
	 * @param content
	 * @param type
	 * @param voice
	 * @param fullscreen
	 * @param rep
	 * @return
	 */
	@RequestMapping("/addschoolnotice")
	@ResponseBody
	public Message addSchoolnotice(String title,String content,String type,Integer voice,Integer fullscreen ,HttpServletResponse rep){
		RepUtil.repPake(rep);
		Message Message=new Message();
		Map<String, Object> data =new HashMap<>();
		if(null!=title&&null!=content&&null!=type&&null!=voice&&null!=fullscreen) {
			HljtSchoolnotify hljtschoolnotify=new HljtSchoolnotify();
			
			hljtschoolnotify.setTitle(title);
			hljtschoolnotify.setContent(content);
			hljtschoolnotify.setType(type);
			hljtschoolnotify.setVoice(voice);
			hljtschoolnotify.setFullscreen(fullscreen);
			Date createtime=new Date();
			hljtschoolnotify.setCreatetime(createtime);
			
			hljtSchoolNotifyServiceImpl.addSchoolnotify(hljtschoolnotify);
			HljtDevice hljtDevice = new HljtDevice();
			hljtDevice.setPattern(2);
			hljtOtherInterfacesService.updateDeviceAllModify(hljtDevice);
			data.put("success", true);
		}else {
			data.put("success", false);
		}
		Message.setData(data);
		return Message;
	}
	
	
	/**
	 * 删除条通知
	 * @param id
	 * @param rep
	 * @return
	 */
	@RequestMapping("/deletehoolnotice")
	@ResponseBody
	public Message deleteSchoolnotice(Integer  id,HttpServletResponse rep){
		RepUtil.repPake(rep);
		Message Message=new Message();
		Map<String, Object> data =new HashMap<>();
		if(null !=id) {
			
			hljtSchoolNotifyServiceImpl.deleteSchoolnotify(id);
			HljtDevice hljtDevice = new HljtDevice();
			hljtDevice.setPattern(2);
			hljtOtherInterfacesService.updateDeviceAllModify(hljtDevice);
			data.put("success", true);
		}else {
			data.put("success", false);
		}
		Message.setData(data);
		return Message;
	}

//=====================================================================================================================================================
	/**
	 * 获取本电脑ip
	 * @return
	 * @throws UnknownHostException
	 */
	 public  String getIp() throws Exception {
	        String ipString = "";
	        Enumeration<NetworkInterface> allNetInterfaces = NetworkInterface.getNetworkInterfaces();
	        InetAddress ip = null;
	        while (allNetInterfaces.hasMoreElements()) {
	            NetworkInterface netInterface = (NetworkInterface) allNetInterfaces.nextElement();
	            Enumeration<InetAddress> addresses = netInterface.getInetAddresses();
	            while (addresses.hasMoreElements()) {
	                ip = (InetAddress) addresses.nextElement();
	                if (ip != null && ip instanceof Inet4Address && !ip.getHostAddress().equals("127.0.0.1")) {
	                    return ip.getHostAddress();
	                }
	            }
	        }
	        return ipString;
	    }
	
	/**
	 * 天气接口
	 * @return
	 */
	 public String getCitys(String cityid) {
		 String host = "http://aliv11.data.moji.com";
		    String path = "/whapi/json/alicityweather/briefforecast6days";
		    String method = "POST";
		    String appcode = "d9a7193a79214bd1b7eba0638ebda488";
		    
		    String city=null;
		    Map<String, String> headers = new HashMap<String, String>();
		    //最后在header中的格式(中间是英文空格)为Authorization:APPCODE 83359fd73fe94948385f570e3c139105
		    headers.put("Authorization", "APPCODE " + appcode);
		    //根据API的要求，定义相对应的Content-Type
		    headers.put("Content-Type", "application/x-www-form-urlencoded; charset=UTF-8");
		    Map<String, String> querys = new HashMap<String, String>();
		    Map<String, String> bodys = new HashMap<String, String>();
		    bodys.put("cityId", cityid);
		    bodys.put("token", "073854b56a84f8a4956ba3e273f6c9d7");


		    try {
		    	/**
		    	* 重要提示如下:
		    	* HttpUtils请从
		    	* https://github.com/aliyun/api-gateway-demo-sign-java/blob/master/src/main/java/com/aliyun/api/gateway/demo/util/HttpUtils.java
		    	* 下载
		    	*
		    	* 相应的依赖请参照
		    	* https://github.com/aliyun/api-gateway-demo-sign-java/blob/master/pom.xml
		    	*/
		    	HttpResponse response = HttpUtils.doPost(host, path, method, headers, querys, bodys);
		    	//System.out.println(response.toString());
		    	//获取response的body
		    	//System.out.println(EntityUtils.toString(response.getEntity()));
		    	city=EntityUtils.toString(response.getEntity());
		    } catch (Exception e) {
		    	e.printStackTrace();
		    }
		return city;
		 
	 }
	
public static void main(String[] args) throws InterruptedException {

//	 Boolean result = false;  
//     while(!result) { 
//    	 Thread.sleep(1 * 1000);
//    	 SimpleDateFormat format = new SimpleDateFormat("HH:mm:ss");
//    	 Date date = new Date();
//    	 if(format.format(date).equals("14:08:00")) {
//    		 System.out.println("06:00:00");
//    	 }
//     }
	SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd");
	Date date = new Date();
	System.out.println(format.format(date));
//	HljtSchoolController HljtSchoolController=new HljtSchoolController();
//	System.out.println(HljtSchoolController.getCitys("2"));
}
	
}
